<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()">
          <i class="el-icon-arrow-left" />返回
        </span>
        <span>|</span>
        <span>{{ title }}</span>
      </div>
      <div class="right">黑马程序员</div>
    </header>
    <main v-if="type != 'edit'" class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :model="addForm" :rules="addRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <!-- :http-request="uploadFn" 上传方式，可以覆盖on-success
                :headers="headers"
                :data="uploadData"
                -->
              <el-upload
                class="avatar-uploader"
                action="https://192.168.0.101:8010/upload"
                :http-request="uploadFn"
                :show-file-list="false"
                :on-success="handleLicenseSuccess"
                :before-upload="beforeLicenseUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <main v-else class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm1" label-width="100px" :model="addForm" :rules="addRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <!-- :http-request="uploadFn" 上传方式，可以覆盖on-success
                :headers="headers"
                :data="uploadData"
                -->
              <el-upload
                ref="upload"
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :http-request="uploadFn"
                :file-list="fileList"
                :auto-upload="false"
              >
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>

              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">联系人信息</div>
        <div class="form">
          <el-form ref="ruleForm2" label-width="100px" :model="addForm" :rules="addRules">
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getIndustryListAPI, uploadAPI, createEnterpriseAPI, getEnterpriseAPI, editEnterpriseAPI } from '@/apis/park'
export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      addRules: {
        name: [
          { required: true, message: '企业名称为必填', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '法人为必填', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '注册地址为必填', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '所在行业为必填', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '企业联系人为必填', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '企业联系人电话为必填', trigger: 'blur' }
        ],
        businessLicenseId: [
          { required: true, message: '请上传营业执照', trigger: 'blur' }
        ]
      },
      industryList: [],
      imageUrl: '',
      // 上传图片的另外一种方式：原生的ajax
      // headers: {
      //   Authorization: `Bearer ${this.$router.store.state.token}`
      // },
      // uploadData: {
      //   type: 'businessLicense'
      // }
      fileList: []
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    },
    type() {
      return this.$route.query.type
    },
    title() {
      if (this.type === 'edit') return '编辑企业信息'
      else if (this.type === 'check') return '查看企业信息'
      else return '添加企业信息'
    },
    imageText() {
      if (!this.imageUrl) {
        return '请选择'
      } else {
        return '查看图片'
      }
    }
  },
  mounted() {
    // eslint-disable-next-line no-sequences
    // this.addForm.name = '雷人加尔',
    // this.addForm.legalPerson = '狗熊',
    // this.addForm.registeredAddress = '广东深圳',
    // this.addForm.contact = '雷恩加尔',
    // this.addForm.contactNumber = '13322206666'
  },
  created() {
    this.getIndustryList()
    if (this.type === 'edit') {
      this.editLicense(this.id)
    }
  },
  methods: {
    async getIndustryList() {
      const res = await getIndustryListAPI()
      this.industryList = res.row
      // console.log(res)
    },
    handleLicenseSuccess() {
    },
    async uploadFn(fileObj) {
      const theFile = fileObj.file
      const fd = new FormData()
      fd.append('file', theFile)
      fd.append('type', 'businessLicense')
      const res = await uploadAPI(fd)
      this.imageUrl = res.data.url
      this.addForm.businessLicenseId = res.data.id
      this.addForm.businessLicenseUrl = res.data.url
      // console.log(res)

      // 营业执照需要单独再校验一次
      await this.$refs.ruleForm.validateField('businessLicenseId')
    },
    beforeLicenseUpload(file) {
      const list = ['image/jpeg', 'image/png']
      const isImage = list.includes(file.type)
      const isSize = (file.size / 1024 / 1024 < 3)
      if (!isImage) {
        this.$message.error('上传的营业执照只能是jpg/png格式！')
      }
      if (!isSize) {
        this.$message.error('上传的营业执照大小不能超过3MB')
      }
      if (isImage && isSize) {
        return true
      } else {
        return Promise.reject('取消发送')
      }
    },
    // 添加企业
    async confirmSubmit() {
      if (this.type === 'edit') {
        await this.$refs.ruleForm1.validate()
        await this.$refs.ruleForm2.validate()
        this.editEnterprise(this.id)
      } else {
        await this.$refs.ruleForm.validate()
        createEnterpriseAPI(this.addForm)
      }
      this.$message({
        message: '当前信息已添加至服务器',
        type: 'success'
      })
      // this.$router.back()
    },
    // 编辑企业信息
    async editLicense(id) {
      const res = await getEnterpriseAPI(id)
      // console.log(res)
      for (const key in this.addForm) {
        this.addForm[key] = res.data[key]
      }
      this.imageUrl = res.data.businessLicenseUrl
      if (this.imageUrl) {
        this.fileList.push({ name: res.data.businessLicenseId, url: res.data.businessLicenseUrl })
      }
    },
    // 上传新的营业执照
    submitUpload() {
      this.$refs.upload.submit()
      // this.uploadFn()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    // 编辑企业信息
    async editEnterprise(id) {
      const data = { ...this.addForm, id }
      const res = await editEnterpriseAPI(data)
      console.log(res)
    }
  }
}

</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
